import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicButtonUI;

import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


	
public class TextEditor extends JFrame{
	protected static JMenuBar menuBar;
	public JTabbedPane getTabPane() {
		return tabPane;
	}

	public void setTabPane(JTabbedPane tabPane) {
		this.tabPane = tabPane;
	}

	protected JTabbedPane tabPane;
	protected JTextArea[] textArea;
	protected String[] fileName;
	protected int tabCount;
	protected static String frameTitle;
	protected int activeTab;
	JPanel pane = new JPanel();
	
	TextEditor() {

		add(pane);
		frameTitle="unbennant.txt - Texteditor";
		menuBar = new JMenuBar();
		tabPane = new JTabbedPane();
		textArea = new JTextArea[20];
		fileName = new String[20];
		tabCount = 0;
		getContentPane().add(tabPane);
		activeTab = 0;
		setTitle(frameTitle);
		
		newTab();
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(800, 600);
		JMenuBar menuBar = new JMenuBar();
		JMenu  fileMenu = new JMenu("Datei");
		menuBar.add(fileMenu);
		setJMenuBar(menuBar);
		
		JMenuItem newAction = new JMenuItem("Neu");
			newAction.addActionListener(new ActionListener() {
				public void actionPerformed( ActionEvent e) {
					newTab();
			}
		});
		newAction.setAccelerator(KeyStroke.getKeyStroke( 'N', InputEvent.CTRL_DOWN_MASK ));
		fileMenu.add(newAction);
		
		fileMenu.add(new JSeparator());
		JMenuItem openAction = new JMenuItem("Öffnen");
		openAction.addActionListener(new ActionListener(){
					public void actionPerformed( ActionEvent e) {
					  JFileChooser chooser = new JFileChooser();
					  chooser.setMultiSelectionEnabled(false);
					  if (chooser.showOpenDialog(chooser) == 
							  JFileChooser.APPROVE_OPTION)
						 if(textArea[0].getText().length()!=0){
							 	newTab();
							 	System.out.println(tabCount);
							 	textArea[tabCount-1].setText(readdata(chooser.getSelectedFile()));
							 	activeTab = tabCount-1;
							 	tabPane.setTitleAt(tabCount-1, fileName[tabCount-1]);
							 	tabPane.setEnabledAt(tabCount-1, true);
							 	
							 
						 } else {
							textArea[activeTab].setText(readdata(chooser.getSelectedFile()));
							refreshTitle();
						 }	 
			}
		});
		openAction.setAccelerator(KeyStroke.getKeyStroke('O', InputEvent.CTRL_DOWN_MASK));
		fileMenu.add(openAction);
		
		JMenuItem saveAction = new JMenuItem( "Speichern" );
		saveAction.addActionListener(new ActionListener () {	 
				public void actionPerformed( ActionEvent e ) {
			    writeData();
			    refreshTitle();
			}
		});
		saveAction.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK));
		fileMenu.add(saveAction);
		
		fileMenu.add(new JSeparator());
		JMenuItem exitAction = new JMenuItem( "Beenden" );
		exitAction.addActionListener(new ActionListener(){
			  public void actionPerformed( ActionEvent e ) {
			    System.exit( 0 );
			}
		});
		exitAction.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
		fileMenu.add( exitAction );
		
		tabPane.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				if(tabPane.getSelectedIndex()> activeTab) {
					activeTab++;
									}
				if(tabPane.getSelectedIndex() < activeTab) {
					activeTab--;
				}
				refreshTitle();
				System.out.println("tab: "+activeTab);
			}
		});
	}
	public void newTab() {
		if(fileName[tabCount] == null) {
			fileName[tabCount] = "unbenannt.txt";
		}
		if(textArea[tabCount] == null) {
			textArea[tabCount] = new JTextArea();
		}
		
		tabPane.insertTab(fileName[tabCount], null, new JScrollPane(textArea[tabCount]), null, tabCount);
		tabPane.setTabComponentAt(tabCount, new Tab(tabPane));
		tabCount++;
	}
	
	public static void main(String[] args) {
		new TextEditor().setVisible(true);
	}
	
	public void refreshTitle() {
		this.setTitle(fileName[activeTab]+" - Texteditor");
		System.out.println(fileName[activeTab]+": "+activeTab);
		
	}
	public void writeData() {	
		JFileChooser fChooser = new JFileChooser();
		File file = null;
		int result = fChooser.showSaveDialog(this);
	
		if (result == JFileChooser.APPROVE_OPTION) {
			file = fChooser.getSelectedFile();
			if (!file.getAbsolutePath().endsWith(".txt"))
				file = new File(file.getAbsolutePath() + ".txt");
			try {
				System.out.print(activeTab);
				textArea[activeTab].write(new FileWriter(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		fileName[activeTab] = file.getName();
		JOptionPane.showMessageDialog(this, "Erfolgreich gespeichert. ", "Speichern", JOptionPane.INFORMATION_MESSAGE);
	
	}
	public String readdata(File file) {
		String data="";
		try{
		    FileReader fr = new FileReader(file);
		    BufferedReader br = new BufferedReader(fr);
		    String zeile = "";

		    while( (zeile = br.readLine()) != null )
		    {
		     if(data == "") {
		    	 data = zeile;
		     } else {
		      data = data+"\n"+zeile;
		     }
		    }
		    br.close();
		    
		} catch( IOException e) {
			data = ""+e;
		} finally{}
	fileName[tabCount-1] = file.getName();
	return data;
	}
	// neuer leerer Tab
	private class Tab extends JPanel {
	    private final JTabbedPane pane;

	    public Tab(final JTabbedPane pane) {
	        super(new FlowLayout(FlowLayout.LEFT, 0, 0));

	        this.pane = pane;
	        setOpaque(false);
	        
	        JLabel label = new JLabel() {
	            public String getText() {
	                int i = pane.indexOfTabComponent(Tab.this);
	                if (i != -1) {
	                    return pane.getTitleAt(i);
	                }
	                return null;
	            }
	        };
	        
	        add(label);
	        
	        label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
	       
	        JButton button = new TabButton();
	        add(button);
	       
	        setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
	    }
	    // neuer Tab + geöffnete Datei
	    public Tab(final JTabbedPane pane, File file) {
	        super(new FlowLayout(FlowLayout.LEFT, 0, 0));

	        this.pane = pane;
	        setOpaque(false);
	        
	        JLabel label = new JLabel() {
	            public String getText() {
	                int i = pane.indexOfTabComponent(Tab.this);
	                if (i != -1) {
	                    return pane.getTitleAt(i);
	                }
	                return null;
	            }
	        };
	        
	        add(label);
	        
	        label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
	       
	        JButton button = new TabButton();
	        add(button);
	       
	        setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
	    }

	    private class TabButton extends JButton implements ActionListener {
	        public TabButton() {
	            int size = 17;
	            setPreferredSize(new Dimension(size, size));
	            setToolTipText("Tab schließen");
	            
	            setUI(new BasicButtonUI());
	            
	            setContentAreaFilled(false);
	            
	            setFocusable(false);
	            setBorder(BorderFactory.createEtchedBorder());
	            setBorderPainted(false);

	            addMouseListener(buttonMouseListener);
	            setRolloverEnabled(true);
	           
	            addActionListener(this);
	        }

	        public void actionPerformed(ActionEvent e) {
	            int i = pane.indexOfTabComponent(Tab.this);
	            if (i != -1) {
	                pane.remove(i);
	                
	                for(int j = i; j < tabCount; j++){
	                	fileName[j] = fileName[j+1];
	                	textArea[j] = textArea[j+1];
	                }
	                tabCount--;
	            }
	        }

	        public void updateUI() {
	        }

	  	        protected void paintComponent(Graphics g) {
	            super.paintComponent(g);
	            Graphics2D g2 = (Graphics2D) g.create();
	            
	            if (getModel().isPressed()) {
	                g2.translate(1, 1);
	            }
	            g2.setStroke(new BasicStroke(2));
	            g2.setColor(Color.BLACK);
	            if (getModel().isRollover()) {
	                g2.setColor(Color.RED);
	            }
	            int delta = 6;
	            g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
	            g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
	            g2.dispose();
	        }
	    }

	    private final MouseListener buttonMouseListener = new MouseAdapter() {
	        public void mouseEntered(MouseEvent e) {
	            Component component = e.getComponent();
	            if (component instanceof AbstractButton) {
	                AbstractButton button = (AbstractButton) component;
	                button.setBorderPainted(true);
	            }
	        }

	        public void mouseExited(MouseEvent e) {
	            Component component = e.getComponent();
	            if (component instanceof AbstractButton) {
	                AbstractButton button = (AbstractButton) component;
	                button.setBorderPainted(false);
	            }
	        }
	    };
	}
}


